/****************************************************************************
 * Copyright 2009 Huascar A. Sanchez                                        *
 *                                                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");          *
 * you may not use this file except in compliance with the License.         *
 * You may obtain a copy of the License at                                  *
 *                                                                          *
 *     http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                          *
 * Unless required by applicable law or agreed to in writing, software      *
 * distributed under the License is distributed on an "AS IS" BASIS,        *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 * See the License for the specific language governing permissions and      *
 * limitations under the License.                                           *
 ****************************************************************************/
package com.gotobject.filter;

import com.gotobject.filter.command.Command;
import static com.gotobject.filter.FilterQ.from;
import static com.gotobject.filter.common.Predicates.gt;
import static com.gotobject.filter.common.Predicates.lt;
import static com.gotobject.filter.common.Transformations.grep;
import static com.gotobject.filter.common.Aggregations.count;
import com.gotobject.filter.spi.Variant;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

import java.util.ArrayList;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileWriter;

/**
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
public class PlayCommandTest {
    @Test
    public void testBasicPlay() throws Exception {
        final List<Integer> list = new ArrayList<Integer>(asList(1, 2, 3));
        final Command<Integer> c = new Command<Integer>(){
            @Override
            public Iterable<Integer> apply(Iterable<? extends Integer> iterable) throws Exception {
                list.add(5);
                return self(iterable);
            }
        };

        c.execute();
        assertEquals(asList(1, 2, 3, 5), list);
    }


    @Test
    public void testActionWithFilteringCap() throws Exception {
        final List<Integer> someList = asList(1, 2, 3, 4);
        final AtomicInteger count = new AtomicInteger();
        from(someList).play(new Command<Integer>(){
            @Override
            public Iterable<Integer> apply(Iterable<? extends Integer> iterable) throws Exception {
                final Iterable<Integer> t = self(iterable);
                for(Integer e : t){
                    count.getAndIncrement();
                    System.out.println(e);
                }
                return t;
            }
        });

        assertEquals("4 elements were printed", 4, count.get());
    }


    @Test
    public void testCompoundActions() throws Exception {
        final List<Integer> someList = asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        final AtomicInteger count = new AtomicInteger();
        from(someList).play(new Command<Integer>(){
            @Override
            public Iterable<Integer> apply(Iterable<? extends Integer> iterable) throws Exception {
                final Iterable<Integer> t = self(iterable);
                from(t).where(gt(4).and(lt(10))).play(new Command<Integer>(){
                    @Override
                    public Iterable<Integer> apply(Iterable<? extends Integer> iterable) throws Exception {
                        final Iterable<Integer> t = self(iterable);
                        for(Integer e: t){
                            System.out.println(e);
                            count.getAndIncrement();
                        }
                        return self(iterable);
                    }
                });
                return t;
            }
        });

        assertEquals("5 elements were found", 5, count.get());
    }

    @Test
    public void testGrepMixedWithCommand() throws Exception {
        final String[] lines = {
                "order was created - transaction started.",
                "order was placed in queue - transaction in progress.",
                "order was delayed - transaction was paused.",
                "order was resumed - transaction was resumed.",
                "order was shipped - transaction in progress.",
                "order was received - transaction was closed."
        };
        final File          temp    = File.createTempFile("aaa",null);
        final PrintWriter   out     = new PrintWriter(new FileWriter(temp));
        try {
            for(String each : lines){
                writeToFile(out, each);
            }

            out.close(); // close it before filtering it.

            final Iterable<Variant<String>> t = from(temp).apply(grep("- transaction in progress."));
            for(Variant<String> each : t){
                System.out.println(String.format("line %s %s",each.key(), each.value()));
            }

            assertEquals("2 elements were found", 2, count(t));
            
        } finally {
            temp.deleteOnExit();
        }
    }

    /**
     * write the result to a file.
     * @param out
     *      a {@link PrintWriter} object.
     * @param entry
     *      line to be written on the file.
     */
    private static void writeToFile(PrintWriter out, String entry) {
        out.println(entry);
    }
}
